<?php

namespace App\Api\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Thumbnail;
use Illuminate\Support\Facades\Storage;
class SandboxController extends Controller
{
    public function index()
    {
		return view('Api.Sandbox.index');
    }

    public function test()
    {

    }
    public function insertT()
    {
        $in_purse_balance = 9999999999999;
//        $in_purse_balance =
        $data = [
            'reasoncode'    =>  1,
            'outuserid'     =>  1,
            'outusertypeid' =>  1,
            'outpursetypeid'=>  1,
            'outpurseid'    =>  1,
            'outamount'     =>  1,
            'outbalance'    =>  1,
            'intouserid'    =>  1,
            'intousertypeid'=>  1,
            'intopursetypeid'=> 1,
            'intopurseid'   =>  1,
            'intoamount'    =>  1,
            'intobalance'   =>  $in_purse_balance, //1316134911
            'detail'        =>  '--'.$in_purse_balance.'--'.sizeof($in_purse_balance).'-'.gettype($in_purse_balance).'-'.PHP_INT_MAX,
            'status'        =>  1,
            'created_at'    =>  date('Y-m-d H:i:s'),
            'updated_at'    =>  date('Y-m-d H:i:s'),
        ];
        DB::connection()->enableQueryLog();
        $id = DB::table('fund_transfer')->insert($data);
        echo '<pre>';print_r(DB::getQueryLog());
        dd($id);
    }
	public function submit(Request $request)
    {
        $result = [];
        $post = $request->all();
        $keys = $post['key'];
        $value = $post['value'];
        $cmd = $post['_cmd'];
        $result['full_url'] = url("/api/{$cmd}");
        $___submit = $post['___submit'];
        unset($post['key'],$post['value'],$post['_cmd'],$post['s'],$post['___submit']);
        $result['request_http'] = '';
		foreach($keys as $k => $v){
			if (empty($v)) continue;
            $post[$v] = htmlspecialchars_decode($value[$k]);
		}
		$data = $post;
		unset($data['sign']);
        if (empty($data['ticket'])){
            unset($data['ticket']);
        }
		ksort($data);
		$str = '';
		foreach ($data as $k => $v)
		{
			$str .= $k . '=' . $v . "&";
		}
        $str = substr($str , 0 , -1);
        $result['request_before_sign_str'] = $str; //签名前的字符串
        $sign = $post['sign'] = md5($str);	// sign 算法
        foreach ($post as $k=>$v) {
            if ($k == 'ticket' && !$v) continue;
            $result['request_http'] .= $k.':'.$v.'<br/>';
        }
        if ($___submit == 'post') {
            $sJson = $this->curlpost($cmd,$post);
            $json = json_decode(trim($sJson,'﻿'),true);
             if (is_array($json) && array_key_exists('__errormore',$json) && $json['__errormore']){
                $result['exception'] = $json['__errormore'];
                unset($json['__errormore']);
            }
        }else {
            $json = null;
        }
/* 
		$this->script_log('生成sign：'.$sign);
		// 设置sign
		$this->script_sign($sign);
		echo '发送的参数：';
		print_r($post);
		// 执行请求
		echo "\n".'返回源JSON：';
		print_r(trim($sJson));
		echo "\n".'格式化JSON：';
		print_r($json);
		// 设置 token
        if($post['_cmd'] == 'user_login') $this->script_token($json['data']['ticket']);
 */
        $result['sign'] = $sign;
        $result['request'] = $post; 
        $result['response'] = $json;
        if($cmd == 'user_login'){ $result['token'] = $json['data']['ticket']; }
        exit(json_encode($result));
    }

	private function curlpost($cmd,$array)
    {
		$post = http_build_query($array);
		$ch = curl_init();

        $url = $_SERVER['HTTP_HOST'] . '/api/' . $cmd;
		//$url = stripos($_SERVER['HTTP_HOST'],'localhost') !== 0 ? $_SERVER['HTTP_HOST'] : 'http://testecf.windonwd.local/api';
		curl_setopt($ch, CURLOPT_URL, $url);
//		curl_setopt($ch, CURLOPT_PORT, '5000');
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
    }

    public function sendSms(Request $request){
        $mobile = $request->get('mobile');
        if($mobile){
            $code = create_smscode($mobile,1);
            $flag = send_msg($mobile, $code);
            if($code){
                view('Api.Sandbox.sendSms')->with('code',$code);
                return json_success('ok',$code);
            }else{
                return json_error('false');
            }
        }
        return view('Api.Sandbox.sendSms');
    }

    public function html(Request $request)
    {
        $filename = $request->input('f');
        if ($filename) {
            return view('Api.Sandbox.html.'.$filename); 
        }
        $files = scandir(resource_path('/views/Api/Sandbox/html'));
        $result = [];
        foreach ($files as $file) {
            if ($file != '.' && $file != '..') {
                $result[] = explode('.',basename($file))[0];
            }
        }
		return view('Api.Sandbox.html',['files'=>$result]);
    }

    public function ffmpeg_test(Request $request)
    {
    // get file from input data
    $file             = $request->file('file');

    // get file type
    $extension_type   = $file->getClientMimeType();
    
    // set storage path to store the file (actual video)
    $destination_path = storage_path().'/uploads';

    // get file extension
    $extension        = $file->getClientOriginalExtension();


    $timestamp        = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
    $file_name        = $timestamp;
    
    $upload_status    = $file->move($destination_path, $file_name);         

    if($upload_status)
    {
      // file type is video
      // set storage path to store the file (image generated for a given video)
      $thumbnail_path   = storage_path().'/images';

      $video_path       = $destination_path.'/'.$file_name;

      // set thumbnail image name
      $thumbnail_image  = "thumbnail.".$timestamp.".jpg";
      
      // set the thumbnail image "palyback" video button
      $water_mark       = storage_path().'/watermark/p.png';

      // get video length and process it
      // assign the value to time_to_image (which will get screenshot of video at that specified seconds)
    //   $time_to_image    = floor(($data['video_length'])/2);


      $thumbnail_status = Thumbnail::getThumbnail($video_path,$thumbnail_path,$thumbnail_image);
    //   $thumbnail_status = Thumbnail::getThumbnail($video_path,$thumbnail_path,$thumbnail_image,$time_to_image);
      if($thumbnail_status)
      {
        echo "Thumbnail generated";
      }
      else
      {
        echo "thumbnail generation has failed";
      }
    }
  }

}